import { ref } from 'vue'
import wellChu1 from '@/assets/map/well-chu-1.png'
import wellChu2 from '@/assets/map/well-chu-2.png'
import wellJie1 from '@/assets/map/well-jie-1.png'
import wellJie2 from '@/assets/map/well-jie-2.png'
import wellShi1 from '@/assets/map/well-shi-1.png'
import wellShi2 from '@/assets/map/well-shi-2.png'
import Bus from '@/utils/bus'
import { showFailToast } from 'vant'

export function useMarker({ AMap, mapInstance, emits }) {
  const markers = ref([])
  // 临时点缓存
  const pointsCache: any = []
  let tempPolyline = null
  // 清除所有标记
  function clearMarkers() {
    markers.value.forEach((marker) => {
      marker.setMap(null)
    })
    markers.value = []
  }

  const getMarkerContent = (item, select = false) => {
    // pointType 井的类型(1:出门井, 2:接户井, 3:市政井)
    let wellTmg = ''
    const { pointType } = item
    if (pointType === 1) {
      if (select) {
        wellTmg = wellChu2
      }
      else {
        wellTmg = wellChu1
      }
    }
    if (pointType === 2) {
      if (select) {
        wellTmg = wellJie2
      }
      else {
        wellTmg = wellJie1
      }
    }
    if (pointType === 3) {
      if (select) {
        wellTmg = wellShi2
      }
      else {
        wellTmg = wellShi1
      }
    }

    let wellDom = `<img src="${wellTmg}" style="width: 23px;height: 30px;"></div>`
    if (select) {
      wellDom = `<img src="${wellTmg}" style="width: 30px;height: 38px;"></div>`
    }
    return wellDom
  }
  // 创建标记
  function createMarker(point, type: 'exit' | 'connect' | 'municipal') {
    const [lng, lat] = point.coordinates.split(',').map(Number)

    const marker = new AMap.value.Marker({
      position: [lng, lat],
      content: getMarkerContent(point),
      offset: new AMap.value.Pixel(-11, -15),
      extData: point,
      bubble: false,
    })

    marker.setMap(mapInstance.value)
    markers.value.push(marker)
    return marker
  }

  // 点击非点位触发
  const mapClickEvent = (event: any) => {
    const lnglat = event.lnglat
    pointsCache.push({
      rtkLongitude: lnglat.lng,
      rtkLatitude: lnglat.lat,
    })
    offClickMarker()
    completeDraw()
    // console.log('一个点为井，一个非井', pointsCache)
  }

  // 点击点位触发
  const markerClickEvent = (event: any) => {
    // 触发事件的地理坐标，AMap.LngLat 类型
    const target = event.target
    const extData = target.getExtData()
    target.setContent(getMarkerContent(extData, true))
    target.setOffset(new AMap.value.Pixel(-15, -19))
    Bus.$emit('showPromot', { show: true, text: '点击终点：出户/接户/市政井或任意位置' })
    // 检查是否已经处理过这个点位
    if (pointsCache.some(point => point.id === extData.id)) {
      return
    }
    pointsCache.push(extData)
    if (pointsCache.length === 2) {
      offClickMarker()
      completeDraw()
      // console.log('两个点为井', pointsCache)
    }
    else {
      mapInstance.value.on('click', mapClickEvent)
    }
  }
  // 提交管线信息
  function submitPipeline() {
    Bus.$emit('refreshTool', true)
    Bus.$emit('showLayerControl', true)
    tempPolyline && tempPolyline.setMap(null)
    emits('addPolyline', pointsCache)
  }
  // 取消绘制管线信息
  function cancelPipeline() {
    Bus.$emit('showLayerControl', true)
    Bus.$emit('refreshTool', true)
    tempPolyline && tempPolyline.setMap(null)
    Object.values(markers.value).forEach((item: any) => {
      item.setContent(getMarkerContent(item.getExtData()))
      item.setOffset(new AMap.value.Pixel(-11, -15))
    })
  }

  function completeDraw() {
    Bus.$emit('showPromot', { show: true, text: '', submit: true })
    // Bus.$emit('showLayerControl', true)
    drawTempPolyline()
  }

  function drawTempPolyline() {
    const [lng, lat] = pointsCache[0].coordinates.split(',').map(Number)
    let secondPos: any = []
    if (pointsCache[1]?.id) {
      secondPos = pointsCache[1].coordinates.split(',').map(Number)
    }
    else {
      secondPos = [pointsCache[1].rtkLongitude, pointsCache[1].rtkLatitude]
    }

    tempPolyline = new AMap.value.Polyline({
      path: [
        [lng, lat],
        secondPos,
      ],
      strokeColor: '#FF0000',
      strokeOpacity: 1,
      strokeWeight: 3,
    })
    tempPolyline.setMap(mapInstance.value)
    Bus.$emit('showPromot', { show: true, text: '', submit: true })
  }
  // 取消绑定点击事件
  const offClickMarker = () => {
    Object.values(markers.value).forEach((item: any) => {
      item.off('click', markerClickEvent)
    })
    mapInstance.value.off('click', mapClickEvent)
    cancelPipeline()
  }

  // 绑定点击事件
  const onClickMarker = () => {
    pointsCache.length = 0
    Object.values(markers.value).forEach((item: any) => {
      item.on('click', markerClickEvent)
    })
    Bus.$emit('showPromot', { show: true, text: '点击起点：出户/接户/市政井' })
  }
  // 更新标记
  function updateMarkers(points, type: 'exit' | 'connect' | 'municipal') {
    if (!points || !points.length)
      return

    points.forEach((point) => {
      createMarker(point, type)
    })
  }

  return {
    markers,
    clearMarkers,
    createMarker,
    updateMarkers,
    onClickMarker,
    offClickMarker,
    submitPipeline,
    cancelPipeline,
  }
}
